package com.jt.www.common.service.impl;

import com.alibaba.fastjson.JSON;
import com.jt.www.common.service.RemindRenewalService;
import com.jt.www.dao.mapper.messageinfo.MessageInfoEntityMapper;
import com.jt.www.model.entity.MessageInfoEntity;
import com.jt.www.model.remote.ins.InsManagerResultVO;
import com.jt.www.model.renewal.HolderResultVO;
import com.jt.www.model.reps.GenericListResponse;
import com.jt.www.model.reps.ResponseData;
import com.jt.www.model.sms.SmsVo;
import com.jt.www.model.vo.InsManagerQo;
import com.jt.www.model.vo.renewal.PolicyMsgQo;
import com.jt.www.remote.ins.InsClient;
import com.jt.www.util.DateUtils;
import com.jt.www.util.JsonUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;

@Service
@SuppressWarnings("unchecked")
public class RemindRenewalServiceImpl implements RemindRenewalService {

    public static final Logger log = LoggerFactory.getLogger(RemindRenewalServiceImpl.class);

    private static final String POLICY_STATUS = "00";//已出单
    private static final String SOURCE = "01";//00（pc） 01（app）
    private static final String CHANNEL_CODE = "edu";
    private static final Integer MESSAGE_TYPE = 4;// 续保

    @Autowired
    private InsClient insClient;

    @Autowired
    private MessageInfoEntityMapper messageInfoEntityMapper;

    @Autowired
    private AmqpTemplate rabbitTemplate;

    @Value("${jtpf.renewal.phone}")
    private String phone;

    @Value("${jtpf.rabbit.queuename.sms}")
    private String smsQueueName;

    @Override
    public void renewalEffect(int open) {

        String findCode = "EDU_" + System.currentTimeMillis();

        PolicyMsgQo policyMsgQo = new PolicyMsgQo();

        List<HolderResultVO> holderList = new ArrayList<HolderResultVO>();

        //获取系统一周后的时间
        String polEndWeek = DateUtils.getAfterWeakTime(DateUtils.DATE_FORMAT_YYYY_MM_DD);
        //获取系统29天后的时间
        String polEndMonth = DateUtils.getAfterDayTime(DateUtils.DATE_FORMAT_YYYY_MM_DD);
        //已出单状态
        policyMsgQo.setPolicyStatus(POLICY_STATUS);

        policyMsgQo.setSource(SOURCE);

        policyMsgQo.setChannelCode(CHANNEL_CODE);

        try {
            log.debug(findCode + "投保中心请求开始时间{}", System.currentTimeMillis());

            //查询保单止期距当前日期一周的保单
            policyMsgQo.setPolicyEndDate(polEndWeek);
            log.debug(findCode + "请求投保中心参数 insManagerQo= {}", JSON.toJSONString(policyMsgQo));
            ResponseEntity<GenericListResponse<HolderResultVO>> responseEntityWeek = insClient.selectPolicyMsg(JSON.toJSONString(policyMsgQo));
            log.info(findCode + "投保中心请求结果(保单止期距当前日期一周){}", JSON.toJSONString(responseEntityWeek));

            //查询保单止期距当前日期一月的保单
            policyMsgQo.setPolicyEndDate(polEndMonth);
            log.debug(findCode + "请求投保中心参数 insManagerQo= {}", JSON.toJSONString(policyMsgQo));
            ResponseEntity<GenericListResponse<HolderResultVO>> responseEntityMonth = insClient.selectPolicyMsg(JSON.toJSONString(policyMsgQo));
            log.info(findCode + "投保中心请求结果(保单止期距当前日期29天){}", JSON.toJSONString(responseEntityMonth));

            log.debug(findCode + "投保中心请求结束时间{}", System.currentTimeMillis());

            if (!CollectionUtils.isEmpty(responseEntityWeek.getBody().getList())) {
                holderList.addAll(responseEntityWeek.getBody().getList());
            }
            if (!CollectionUtils.isEmpty(responseEntityMonth.getBody().getList())) {
                holderList.addAll(responseEntityMonth.getBody().getList());
            }

            //遍历list 发送续保提醒短信
            String msg = "";
            SmsVo smsVo = new SmsVo();
            for (HolderResultVO v : holderList) {
                if (open != 2) {//测试时使用 open = 2
                    phone = v.getHolderPhone();
                }
                msg = "【江泰我学保】 您购买的\"" + v.getProductName()
                        + "\"产品（保单号：" + v.getPolicyNo() + "，保险止期：" + v.getPolicyEndDate()
                        + "）即将到期，为保障您的保险权益，请您及时登录我学保公众号续保。";
/*
                EmaySMSUtil.sendSMS(phone, msg);
*/
                smsVo.setMsg(msg);
                smsVo.setPhones(phone);

                log.info(findCode + " 向消息队列推送消息开始 发送短信号码{}", phone);
                rabbitTemplate.convertAndSend(smsQueueName, JsonUtil.object2Json(smsVo));
                log.debug(findCode + " 发送短信号码{} 短信内容{}", phone, msg);

                /*ResponseEntity<GenericResponse> code = smsClient.sendSms(CHANNEL_CODE,smsVo);
                if(!code.getStatusCode().equals(HttpStatus.OK)){
                   throw  new Exception("发送续保短信失败");
                }*/
            }

            // 待续保保单
            List<MessageInfoEntity> msgs = new ArrayList<>();
            // 保险到期前29天
            List<MessageInfoEntity> l1 = getMssageList(polEndMonth);
            // 保险到期前一周
            List<MessageInfoEntity> l2 = getMssageList(polEndWeek);

            if (l1 != null && l1.size() > 0) {
                msgs.addAll(l1);
            }
            if (l2 != null && l2.size() > 0) {
                msgs.addAll(l2);
            }
            if (msgs != null && msgs.size() > 0) {
                messageInfoEntityMapper.insertList(msgs);
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error("查询投保单信息异常");
        }
    }

    private List<MessageInfoEntity> getMssageList(String polEndDate) {
        List<MessageInfoEntity> msgs = new ArrayList<>();
        InsManagerQo qo = new InsManagerQo();
        qo.setPolEndFrom(polEndDate);
        qo.setPolEndEnd(polEndDate);
        ResponseData rets = null;
        try {
            rets = insClient.selectEduPcRenewalList(JSON.toJSONString(qo));
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (rets != null && rets.getList() != null && rets.getTotal() > 0) {
            //投保中心返回的结果集
            List<InsManagerResultVO> list = (List<InsManagerResultVO>) rets.getList();
            list = JSON.parseArray(JSON.toJSONString(list), InsManagerResultVO.class);

            list.forEach(e -> {
                MessageInfoEntity entity = new MessageInfoEntity();
                entity.setNoticeState(false);
                entity.setCreateTime(DateUtils.getCurrentTime());
                entity.setMessageTitle("续保提醒");
                entity.setMessageContent("您的" + e.getProductName() + "产品（投保单号：" + e.getAppCode() + "）即将到期，立即续保以保障校园财产安全、师生人身安全。");
                entity.setIsDeleted(false);
                entity.setTargetUser(e.getHolderCode());
                entity.setMessageType(MESSAGE_TYPE);
                entity.setNoticeType(0);
                entity.setRecordType(1);
                entity.setMessageUrl("/userCenter/insurlist");
                msgs.add(entity);
            });
            return msgs;
        }
        return null;
    }
}
